package com.cf.main;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

public class FindKNeighbors implements Base {
	/**
	 * This method is used to find the nearest K neighbors to an user
	 * @param score
	 * @param i
	 * @param similarityMatrix
	 * @return
	 */
	// 该方法有三个参数，i为用户编号；user_movie_base表示用户-项目评分矩阵；similarityMatrix表示相似矩阵
	public List<Neighbor> findKNeighbors(int i, int[][] user_movie_base, double[][] similarityMatrix) {
		TreeSet<Neighbor> neighborsSet = new TreeSet<Neighbor>();
		List<Neighbor> neighborSerial = new ArrayList<Neighbor>();
		for (int j = 0; j < USERSIZE; j++) {
			if(i != j)
				neighborsSet.add(new Neighbor(j, similarityMatrix[i][j]));
		}
		
		int j = 0 ;
		Iterator<Neighbor> it = neighborsSet.iterator();
		Neighbor nb = null;
		while (j < KNEIGHBOUR && it.hasNext()) {
			nb = it.next();
			if (!equal(nb.getValue(), 0.0d)) {
				neighborSerial.add(it.next());
				j++;
			}
		}
		//System.out.println(i + "  ---" + neighborSerial.toString());
		return neighborSerial;
	}
	
	static boolean equal(double num1, double num2) {
		if ((num1 - num2 > -0.000001) && (num1 - num2) < 0.000001)
			return true;
		else
			return false;
	}
}
